package com.example.petstoreservice.service;

import com.example.petstoreservice.entity.User;
import com.example.petstoreservice.mapper.UserMapper;
import com.example.petstoreservice.utils.Md5Util;
import com.example.petstoreservice.utils.UsernameGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public boolean insertUser(User user){
        String username;
        do{
            UsernameGeneratorUtil usernameGeneratorUtil = new UsernameGeneratorUtil(user.getUsername());
            username = usernameGeneratorUtil.generatorUsername();
        } while(findByUsername(username) != null);

        user.setNickname(username);
        user.setUsername(username);
        String plainPassword = user.getPassword();
        String hashedPassword = Md5Util.getMD5String(plainPassword);
        user.setPassword(hashedPassword);
        int affectRow = userMapper.insertUser(user);
        return affectRow > 0;
    }

    public User findByUsername(String username){
        return userMapper.findByUsername(username);
    }

    public int updatePassword(String username, String newPassword){
        User currentUser = findByUsername(username);

        if (currentUser == null) {
            return 0;
        }

        String Password = Md5Util.getMD5String(newPassword);
        if (Password.equals(currentUser.getPassword())) {
            return 1;
        }

        int updateResult = userMapper.updatePassword(username, Password);

        if (updateResult > 0) {
            return 2;
        } else {
            return 3;
        }
    }

    public boolean updateUser(User user){
        int affectRow = userMapper.updateUser(user);
        return affectRow > 0;
    }

    public boolean deleteUser(String username) {
        int affectRow = userMapper.deleteUser(username);
        return affectRow > 0;
    }
}
